package com.study.d012Components;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.image.PixelReader;
import javafx.scene.layout.AnchorPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

/** 将图片字符化
*@description
*@author xtayhame
*date 2020年3月7日
*version
*since v1.0
*/
public class ImageMain extends Application{
	public static void main(String[] args) {
		launch(args);
	}

	@Override
	public void start(Stage stage) throws Exception {
		AnchorPane anchorPane = new AnchorPane();

		Image image = null;
		//加载方式1
		image = new Image(new FileInputStream(new File("E:\\javafxworkspace\\lianxidemo\\src\\image\\timg3.jpg")));

		ImageView iv = new ImageView(image);
		anchorPane.getChildren().add(iv);

		StringBuffer sb = new StringBuffer();
		PixelReader pixelReader= image.getPixelReader();
		for(int m=0;m<image.getWidth();m++){
			for(int n=0;n<image.getHeight();n++){
				Color color= pixelReader.getColor(m, n);
				//这里用一种颜色的值就可以了
				int red=(int)(color.getRed() * 255);
				//int green=(int)(color.getGreen()  * 255);
				//int blue=(int)(color.getBlue() * 255);
				//根据颜色值返回对应的字符
				sb.append(getStr(red));
			}
			//换行
			sb.append("\r\n");
		}
		write(sb);

		stage.setScene(new Scene(anchorPane, 800, 600));
		stage.show();
	}

	String[]  array = new String[]{" ","a","b","c","E","F","G","H","I","G","K","L","M","N","O","P","Q","R",
			"S","T","U","V","W","@","$","#"};
	public String getStr(int value){
		String str = array[(int)(value/10)];
		return str;
	}

	public void write(StringBuffer sb){
		FileWriter fw = null;
		try {
			fw = new FileWriter(new File("imageTotext.txt"));
			fw.write(sb.toString());
			fw.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			if(fw !=null){
				try {
					fw.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		System.out.println("写入完毕.");

	}

}
